<template>
	<a-modal :centered="true" open :title="C_Title" width="416px" @cancel="CloseModal">
		<div class="add-edit-account">
			<a-form ref="formRef" class="no-required-flag-form" layout="horizontal" :model="formData" :rules="C_Rules">
				<div class="add-edit-account-item" style="margin-top: -32px">真实姓名</div>
				<a-form-item name="userName" label-align="left">
					<a-input
						v-model:value="formData.userName"
						style="width: 336px; height: 36px"
						autocomplete="off"
						placeholder="请输入"
						:maxlength="10"
					></a-input>
				</a-form-item>

				<a-form-item name="phone" label-align="left">
					<div class="add-edit-account-item">手机号</div>
					<a-input
						v-model:value.trim="formData.phone"
						:disabled="!!props.userId"
						style="width: 336px; height: 36px"
						autocomplete="off"
						placeholder="请输入"
						:maxlength="11"
					></a-input>
				</a-form-item>

				<a-form-item name="roleId" label-align="left">
					<div class="add-edit-account-item">角色</div>
					<a-select
						v-model:value="formData.roleId"
						:options="C_Roles"
						style="width: 336px; height: 36px"
						:disabled="Number(formData.roleId) === 1"
						placeholder="请选择"
						:get-popup-container="
							(triggerNode: any) => {
								return triggerNode.parentNode;
							}
						"
					></a-select>
				</a-form-item>

				<div v-if="!props.userId">
					<a-form-item name="password" label-align="left">
						<div class="add-edit-account-item">密码</div>
						<a-input-password
							v-model:value.trim="formData.password"
							:maxlength="20"
							:min="6"
							style="width: 336px; height: 36px"
							placeholder="请输入"
						></a-input-password>
					</a-form-item>

					<a-form-item name="confirmPassword" label-align="left">
						<div class="add-edit-account-item">确认密码</div>
						<a-input-password
							v-model:value.trim="formData.confirmPassword"
							:maxlength="20"
							style="width: 336px; height: 36px"
							placeholder="请输入"
						></a-input-password>
					</a-form-item>
				</div>
			</a-form>
		</div>

		<template #footer>
			<a-button class="btn-default" @click="CloseModal">取消</a-button>
			<a-button type="primary" :loading="loading" @click="SaveForm">{{ !props.userId ? '创建' : '保存' }}</a-button>
		</template>
	</a-modal>
</template>

<script setup lang="ts" name="add-edit-account">
import { g6RegValidate } from 'glasssix-utils-ts';
import type { Rule } from 'ant-design-vue/es/form';
import { useRoleSelects } from '@/global-hooks/selects.hooks';
import { useG6Crypto } from '@/global-hooks/base.hooks';
import { AccountAPI } from '../../../api';
import { TsAccountForm, TsAccountModalType } from '../../../type';
const props = withDefaults(defineProps<{ userId: string | number; type: TsAccountModalType }>(), {
	type: 'addEdit',
	userId: ''
});
const emits = defineEmits<{
	(e: 'ok', flag: 'create' | 'edit', oldId: string | number): void;
	(e: 'update:type', value: ''): void;
}>();
const $message: any = inject('$message');

const { roleOpts } = useRoleSelects();
const { cryptoObj } = useG6Crypto();

const loading = ref<boolean>(false);
const formRef = ref();
const formData = reactive<TsAccountForm>({
	userName: '',
	phone: '',
	roleId: undefined,
	password: '',
	confirmPassword: ''
});

const GetEditData = async (): Promise<void> => {
	const res: TsRes = await AccountAPI.detail(props.userId);
	if (res.code === 0) {
		formData.userName = res.data.userName;
		formData.phone = res.data.phone;
		formData.roleId = res.data.roleId;
	}
};

const CloseModal = (): any => {
	emits('update:type', '');
};

const SaveForm = (): any => {
	g6RegValidate.formSubmit(formRef.value, async () => {
		loading.value = true;

		const newForm = JSON.parse(JSON.stringify(formData));
		if (props.userId) {
			newForm.id = props.userId;
			newForm.changeSuperFlag = 0;
			delete newForm.password;
			delete newForm.confirmPassword;
		}

		try {
			const cryptoData = cryptoObj.enCryptoFun(newForm);
			const res: TsRes = !props.userId ? await AccountAPI.add(cryptoData) : await AccountAPI.edit(cryptoData);
			if (res.code === 0) {
				$message.success(`${!props.userId ? '新增账号成功' : '编辑账号成功'}`);
				CloseModal();
				emits('ok', !props.userId ? 'create' : 'edit', props.userId);
			}
		} finally {
			loading.value = false;
		}
	});
};

const C_Title = computed(() => (!props.userId ? '创建账号' : '编辑账号'));

const C_Rules = computed(() => {
	const rules: Record<string, Rule[]> = {
		userName: [{ required: true, message: '请输入姓名' }],
		phone: [{ required: true, validator: g6RegValidate.checkPhone, trigger: 'blur' }],
		roleId: [{ required: true, message: '请选择角色' }]
	};

	// eslint-disable-next-line no-useless-escape
	const reg = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&\_+\-*/.])(?!.*[\u4E00-\u9FFF]).{6,32}$/;
	const regErrorText = '密码必须包含数字、字母、字符且不少于6位';

	if (!props.userId) {
		rules.password = [
			{
				required: true,
				validator: (rule: Rule, value: string) =>
					g6RegValidate.checkPassword(rule, value, {
						regex: reg,
						noValueTxt: '请输入新密码',
						errRegexTxt: regErrorText
					})
			}
		];
		rules.confirmPassword = [
			{
				required: true,
				validator: (rule: Rule, value: string) =>
					g6RegValidate.checkPassword(rule, value, {
						regex: reg,
						noValueTxt: '请输入确认密码',
						errRegexTxt: regErrorText,
						isSecond: true,
						firstValue: formData.password
					})
			}
		];
	}
	return rules;
});

const C_Roles = computed(() => {
	const newArr = JSON.parse(JSON.stringify(roleOpts.value));
	if (Number(formData.roleId) === 1) {
		newArr.unshift({ label: '超级管理员', value: 1 });
	}

	return newArr;
});

const watchStop = watch(
	() => formData.userName,
	() => {
		formData.userName = formData.userName.replace(/\s+/, '');
	}
);

onMounted(async () => {
	props.userId && GetEditData();
});
onUnmounted(() => {
	watchStop();
});
</script>

<style lang="less">
.add-edit-account {
	display: flex;
	padding: 40px 32px;
	justify-content: center;

	.ant-modal,
	.ant-modal-body {
		padding-top: 0 !important;
	}

	:where(.css-dev-only-do-not-override-kqecok).ant-select-single:not(.ant-select-customize-input) .ant-select-selector {
		height: 36px !important;
	}

	.add-edit-account-item {
		margin-bottom: 8px;
		padding-top: 32px;
		line-height: 22px; /* 157.143% */
		color: @text02;
	}

	.ant-select-selection-placeholder {
		color: rgba(16, 16, 20, 0.2);
	}

	.ant-select-selector,
	.ant-input-password {
		border: 1px solid @borderColor02 !important;
		border-radius: 6px !important;
		color: @text01 !important;
		background-color: transparent !important;
	}
}
</style>
